package com.taxshare.purchaser.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.taxshare.minio.dto.MinIOUploadResDTO;
import com.taxshare.minio.utils.MinIOUtils;
import com.taxshare.mybatis.pager.PageHelp;
import com.taxshare.mybatis.pager.PageRequest;
import com.taxshare.purchaser.constant.CodeConstant;
import com.taxshare.purchaser.constant.ResultConstant;
import com.taxshare.purchaser.entity.*;
import com.taxshare.purchaser.entity.model.InvoiceDetailModel;
import com.taxshare.purchaser.entity.model.InvoiceMainInfoModel;
import com.taxshare.purchaser.mapper.*;
import com.taxshare.purchaser.remote.ApiClientService;
import com.taxshare.purchaser.service.rulesReview.CheckInfoRespVO;
import com.taxshare.purchaser.service.rulesReview.RulesReview;
import com.taxshare.purchaser.util.GraphicsInvoiceUtil;
import com.taxshare.purchaser.util.InvoiceCheckUtil;
import com.taxshare.purchaser.util.PdfchangeOneImg;
import com.taxshare.purchaser.view.dto.*;
import com.taxshare.purchaser.view.vo.*;
import com.taxshare.response.beans.Response;
import com.taxshare.tools.token.UserInfoUtil;
import com.taxshare.tools.util.*;
import io.minio.MinioClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;
import java.util.stream.Collectors;

import static com.taxshare.purchaser.constant.MinIOConstant.BUCKET_NAME;
import static com.taxshare.purchaser.constant.MinIOConstant.GROUP_INVOICE;


/**
 * @author YANG
 * @date 2021/4/2
 * @Description:发票采集
 */
@Slf4j
@Service
public class InvoiceCollectionService extends ServiceImpl<InvoiceCollectionMapper, InvoiceCollectionEntity> {

    private static String timeStart = " 00:00:00";
    private static String timeEnd = " 23:59:59";

    @Autowired
    CheckLogMapper checkLogMapper;

    @Autowired
    TrainTicketMapper trainTicketMapper;

    @Autowired
    TaxiTicketMapper taxiTicketMapper;

    @Autowired
    PlaneTicketMapper planeTicketMapper;

    @Autowired
    PlaneTicketDetailMapper planeTicketDetailMapper;

    @Autowired
    RulesReview rulesReview;

    @Autowired
    QuotaTicketMapper quotaTicketMapper;

    @Autowired
    InvoiceReviewRulesMapper reviewRulesMapper;

    @Autowired
    TollTicketMapper tollTicketMapper;

    @Autowired
    BusTicketMapper busTicketMapper;

    @Autowired
    MachinTicketMapper machinTicketMapper;

    @Autowired
    InvoiceDetailService invoiceDetailService;

    @Autowired
    PlaneTicketDetailService planeTicketDetailService;

    @Autowired
    InvoicePoolService invoicePoolService;

    @Autowired
    InvoicePoolMapper invoicePoolMapper;

    @Autowired
    ApplicationRecordDetailMapper applicationRecordDetailMapper;

    @Autowired
    ApplicationRecordMapper applicationRecordMapper;

    @Autowired
    MinIOUtils minIOUtils;

    @Autowired
    ApiClientService apiClientService;

    @Autowired
    MinioClient instance;

    @Autowired
    InvoiceReviewRulesMapper ReviewRulesMapper;

    @Autowired
    InvoiceReviewRulesService reviewRulesService;

    @Autowired
    CommService commService;
    /**
     * 发票采集【发票采集信息查询】
     *
     * @param query
     * @return
     */
    public Response invoiceCollectionQuery(PageRequest<InvoiceCollectionDTO> query) {
        QueryWrapper<InvoiceCollectionEntity> invoiceQuery = new QueryWrapper<>();
        InvoiceCollectionDTO invoiceCollectionDTO = query.getInfo();
        String selectFlag = invoiceCollectionDTO.getSelectFlag();
        if (StrUtil.isNotBlank(invoiceCollectionDTO.getInvoiceCode())) {
            invoiceQuery.eq("invoice_code", invoiceCollectionDTO.getInvoiceCode());
        }
        if (StrUtil.isNotBlank(invoiceCollectionDTO.getCheckStatus())) {
            invoiceQuery.eq("check_status", invoiceCollectionDTO.getCheckStatus());
        }
        if (StrUtil.isNotBlank(invoiceCollectionDTO.getInvoiceNo())) {
            invoiceQuery.eq("invoice_no", invoiceCollectionDTO.getInvoiceNo());
        }
        if (StrUtil.isNotBlank(invoiceCollectionDTO.getInvoiceType())) {
            invoiceQuery.eq("invoice_type", invoiceCollectionDTO.getInvoiceType());
        }
        if (StrUtil.isNotBlank(invoiceCollectionDTO.getInvoiceState())) {
            invoiceQuery.eq("invoice_state", invoiceCollectionDTO.getInvoiceState());
        }
        if (StrUtil.isNotBlank(invoiceCollectionDTO.getInvoiceDateStart()) && StrUtil.isNotBlank(invoiceCollectionDTO.getInvoiceDateEnd())) {
            invoiceQuery.between("invoice_date", invoiceCollectionDTO.getInvoiceDateStart(), invoiceCollectionDTO.getInvoiceDateEnd());
        }
        String createTimeStrStart = invoiceCollectionDTO.getCreateTimeStartStr();
        String createTimeStrEnd = invoiceCollectionDTO.getCreateTimeEndStr();
        if (StrUtil.isNotBlank(createTimeStrStart) && StrUtil.isNotBlank(createTimeStrEnd)) {
            invoiceQuery.between("create_time_str", createTimeStrStart + timeStart, createTimeStrEnd + timeEnd);
        }
        //权限处理
        if (StrUtil.isNotBlank(UserInfoUtil.getUserID())) {
            if (CodeConstant.GENERAL_TYPE.equals(UserInfoUtil.getUserType())) {
                invoiceQuery.and((invoice ->
                        invoice.eq("person_liable_id", UserInfoUtil.getUserID())//责任人
                                .or().eq("collector_id", UserInfoUtil.getUserID())//采集人
                                .or().like("licensee_id", UserInfoUtil.getUserID())));//被授权人
            }
        }
        //查询页面判断标志 采集页面查询传1，未报销传2，已报销传3
        if (StrUtil.isNotBlank(selectFlag)) {
            if (CodeConstant.FLAG_WBX.equals(selectFlag)) {
                invoiceQuery.in("reimbursement_status", CodeConstant.NOT_REIMBURSEMENT);
            } else if (CodeConstant.FLAG_YBX.equals(selectFlag)) {
                invoiceQuery.eq("reimbursement_status", CodeConstant.REIMBURSEMENT_2);
            } else if (CodeConstant.FLAG_FPCJ.equals(selectFlag)) {
                if (StrUtil.isNotBlank(invoiceCollectionDTO.getReimbursementStatus())) {
                    invoiceQuery.eq("reimbursement_status", invoiceCollectionDTO.getReimbursementStatus());
                }
            }
        } else {
            return Response.error("PUR_107");
        }
        invoiceQuery.ne("collect_mark",CodeConstant.COMM_CODE_1);
        invoiceQuery.orderByDesc("create_time");
        IPage<InvoiceCollectionEntity> invoiceCollectionEntities = PageHelp.siamplePage(this, invoiceQuery, query.getPage(), InvoiceCollectionEntity.class);
        return Response.success(invoiceCollectionEntities);
    }

    /**
     * 发票采集【发票明细查看】
     *
     * @param query
     * @return
     */
    public Response invoiceDetailQuery(PageRequest<InvoiceCollectionDTO> query) {
        QueryWrapper<InvoiceDetailEntity> detailQuery = new QueryWrapper<>();
        InvoiceCollectionDTO invoiceCollectionDTO = query.getInfo();
        detailQuery.eq("link_id", invoiceCollectionDTO.getUuid());
        IPage<InvoiceDetailEntity> invoiceDetailEntityIPage = PageHelp.siamplePage(invoiceDetailService, detailQuery, query.getPage(), InvoiceDetailEntity.class);
        return Response.success(invoiceDetailEntityIPage);
    }

    /**
     * 发票采集【发票信息删除】
     *
     * @param invoiceCollectionDTO
     * @return
     */
    public Response invoiceDelete(InvoiceCollectionDTO invoiceCollectionDTO) {
        List<String> uuidList = invoiceCollectionDTO.getUuidList();
        if (CollUtil.isNotEmpty(uuidList)) {
            QueryWrapper<InvoiceCollectionEntity> invoiceQuery = new QueryWrapper<>();
            invoiceQuery.in("uuid", uuidList);
            invoiceQuery.eq("reimbursement_status", CodeConstant.REIMBURSEMENT_2);
            if (baseMapper.selectCount(invoiceQuery) > 0) {
                return Response.error("PUR_103");
            }
            baseMapper.delete(new QueryWrapper<InvoiceCollectionEntity>().in("uuid", uuidList));
            invoiceDetailService.remove(new QueryWrapper<InvoiceDetailEntity>().in("link_id", uuidList));
        } else {
            return Response.error("PUR_201");
        }
        return Response.success();
    }

    /**
     * 发票采集【手工录入】
     *
     * @param handEnterDTO
     * @return
     */
    public Response handEnter(HandEnterDTO handEnterDTO) {
        //校验采集表中是否存在
        QueryWrapper<InvoiceCollectionEntity> invoiceQuery = new QueryWrapper<>();
        invoiceQuery.eq("invoice_code", handEnterDTO.getInvoiceCode());
        invoiceQuery.eq("invoice_no", handEnterDTO.getInvoiceNo());
        if (baseMapper.selectCount(invoiceQuery) > 0) {
            return Response.error("PUR_101");
        }
        String uuid = UUIDUitl.UUID32(false);
        CheckLogEntity checkLogEntity = new CheckLogEntity();
        BeanUtil.copyProperties(handEnterDTO, checkLogEntity);
        checkLogEntity.setUuid(UUIDUitl.UUID32(false));
        checkLogEntity.setLinkId(uuid);
        checkLogEntity.setDataSource(CodeConstant.UPLOAD_2);
        checkLogMapper.insert(checkLogEntity);
        InvoiceCollectionEntity invoiceCollectionEntity = new InvoiceCollectionEntity();
        BeanUtil.copyProperties(handEnterDTO, invoiceCollectionEntity);
        invoiceCollectionEntity.setUuid(uuid);
        invoiceCollectionEntity.setDataSource(CodeConstant.UPLOAD_2);
        invoiceCollectionEntity.setCollector(UserInfoUtil.getUserNickName());
        invoiceCollectionEntity.setCollectorId(UserInfoUtil.getUserID());
        if (handEnterDTO.getMark() != "1") {
            invoiceCollectionEntity.setReimbursementStatus(CodeConstant.REIMBURSEMENT_1);
            invoiceCollectionEntity.setPersonLiable(UserInfoUtil.getUserNickName());
            invoiceCollectionEntity.setPersonLiableId(UserInfoUtil.getUserID());
            invoiceCollectionEntity.setProcedureStatus(CodeConstant.APPROVAL_1);
        }
        invoiceCollectionEntity.setCheckStatus(CodeConstant.NOT_CHECK);
        invoiceCollectionEntity.setRulesStatus(CodeConstant.NOT_RULES);
        invoiceCollectionEntity.setSubmitStatus(CodeConstant.SUBMIT_STATUS_0);
        invoiceCollectionEntity.setCheckNumber(0);
        invoiceCollectionEntity.setCreateTimeStr(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        if ("1".equals(handEnterDTO.getMark())) {
            invoiceCollectionEntity.setCollectMark(handEnterDTO.getMark());
        } else {
            invoiceCollectionEntity.setCollectMark(CodeConstant.COMM_CODE_0);
        }
        this.save(invoiceCollectionEntity);
        //封装查验所需报文
        CheckInvoiceDTO checkInvoiceDTO = new CheckInvoiceDTO();
        BeanUtil.copyProperties(handEnterDTO, checkInvoiceDTO);
        checkInvoiceDTO.setUuid(uuid);
        return checkInvoiceSync(checkInvoiceDTO);
    }

    /**
     * 发票查验
     *
     * @param handEnterDTO
     * @return
     */
    public Response invoiceCheck(HandEnterDTO handEnterDTO) {
        if (StrUtil.isBlank(handEnterDTO.getUuid())) {
            return Response.error("PUR_108");
        }
        CheckInvoiceDTO checkInvoiceDTO = new CheckInvoiceDTO();
        BeanUtil.copyProperties(handEnterDTO, checkInvoiceDTO);
        return checkInvoiceSync(checkInvoiceDTO);
    }

    //同步查验发票【用于手工录入查验和图片上传识别查验】
    private Response checkInvoiceSync(CheckInvoiceDTO checkInvoiceDTO) {
        return checkInvoice(checkInvoiceDTO);
    }

    //异步查验发票【用于定时任务查验和大批量发票查验】
    @Async
    public void checkInvoiceAsync(CheckInvoiceDTO checkInvoiceDTO) {
        checkInvoice(checkInvoiceDTO);
    }

    //组装数据，同步远程调用查验接口
    private Response checkInvoice(CheckInvoiceDTO checkInvoiceDTO) {
        String uuid = checkInvoiceDTO.getUuid();
        CheckLogChangeVO checkLogChangeVO = new CheckLogChangeVO();
        CheckLogEntity checkLogEntity = new CheckLogEntity();
        InvoiceChangeVO invoiceChangeVO = new InvoiceChangeVO();
        InvoiceCollectionEntity invoiceCollectionEntity = new InvoiceCollectionEntity();
        Response response = null;
        try {
            response = apiClientService.invoiceCheck(checkInvoiceDTO);
        } catch (Exception e) {
            log.error("查验接口异常：{}", e);
            updateFailLogAndCollectionInfo("发票查验异常", checkInvoiceDTO);
            return Response.error("PUR_ERROR_002");
        }
        //T0000接口调用成功
        if (CodeConstant.T0000.equals(response.getCode())) {
            Map resMap = (Map) response.getData();
            PurchaserApiRespVO checkRespVO = BeanUtil.mapToBean((Map<?, ?>) resMap, PurchaserApiRespVO.class, false);
            String checkMsg = checkRespVO.getMsg();
            //查验成功，处理查验返回数据
            if (CodeConstant.SUCCESS.equals(checkRespVO.getCode())) {
                Map<String, Object> checkMap = InvoiceCheckUtil.assembly(checkRespVO.getContent());
                InvoiceMainInfoModel mainInfoModel = (InvoiceMainInfoModel) checkMap.get("invoiceMainInfo");
                mainInfoModel.setKprq(getFormatDate(mainInfoModel.getKprq()));
                List<InvoiceDetailModel> detailModelList = (List<InvoiceDetailModel>) checkMap.get("invoiceDetailInfo");
                //更新发票查验日志
                BeanSelfUtils.copyBean(mainInfoModel, checkLogChangeVO);
                BeanUtil.copyProperties(checkLogChangeVO, checkLogEntity);
                checkLogEntity.setCheckStatus(CodeConstant.CHECK_SUCCESS);
                checkLogEntity.setCheckResult(checkMsg);
                checkLogEntity.setUuid(UUIDUitl.UUID32(false));
                //补全采集发票数据
                BeanSelfUtils.copyBean(mainInfoModel, invoiceChangeVO);
                BeanUtil.copyProperties(invoiceChangeVO, invoiceCollectionEntity);
                invoiceCollectionEntity.setCheckStatus(CodeConstant.CHECK_SUCCESS);
                invoiceCollectionEntity.setCheckResult(checkMsg);
                invoiceCollectionEntity.setInvoiceStatus(InvoiceCheckUtil.transInvoiceStatus(invoiceCollectionEntity.getInvoiceStatus()));
                invoiceCollectionEntity.setUuid(uuid);
                //取校验码后6位
                if (StrUtil.isNotBlank(invoiceCollectionEntity.getCheckCode()) && invoiceCollectionEntity.getCheckCode().length() >= 6) {
                    invoiceCollectionEntity.setCheckCode(invoiceCollectionEntity.getCheckCode().substring(invoiceCollectionEntity.getCheckCode().length() - 6));
                }
                baseMapper.updateById(invoiceCollectionEntity);
                //发票审核规则
                try {
                    InvoiceCollectionEntity entity = checkInvoiceRules(invoiceCollectionEntity);
                    if (entity!=null){
                        checkLogEntity.setRulesStatus(entity.getRulesStatus());
                    }
                    checkLogMapper.insert(checkLogEntity);
                } catch (Exception e) {
                    e.printStackTrace();
                    log.error("审核异常：{}", e);
                    return Response.error("PUR_ERROR_008");
                }
                //处理明细并入表
                List<InvoiceDetailEntity> invoiceDetailEntities = new ArrayList<>();
                for (InvoiceDetailModel invoiceDetailModel : detailModelList) {
                    InvoiceDetailChangeVO invoiceDetailChangeVO = new InvoiceDetailChangeVO();
                    InvoiceDetailEntity invoiceDetailEntity = new InvoiceDetailEntity();
                    BeanSelfUtils.copyBean(invoiceDetailModel, invoiceDetailChangeVO);
                    BeanUtil.copyProperties(invoiceDetailChangeVO, invoiceDetailEntity);
                    invoiceDetailEntity.setUuid(UUIDUitl.UUID32(false));
                    invoiceDetailEntity.setLinkId(uuid);
                    invoiceDetailEntity.setInvoiceCode(invoiceCollectionEntity.getInvoiceCode());
                    invoiceDetailEntity.setInvoiceNo(invoiceCollectionEntity.getInvoiceNo());
                    if (StrUtil.isBlank(invoiceDetailEntity.getModel())) {
                        invoiceDetailEntity.setModel("");
                    }
                    if (StrUtil.isBlank(invoiceDetailEntity.getUnit())) {
                        invoiceDetailEntity.setUnit("");
                    }
                    if (StrUtil.isBlank(invoiceDetailEntity.getGoodsNumber())) {
                        invoiceDetailEntity.setGoodsNumber("0");
                    }
                    invoiceDetailEntities.add(invoiceDetailEntity);
                }
                invoiceDetailService.remove(new QueryWrapper<InvoiceDetailEntity>().eq("link_id", uuid));
                invoiceDetailService.saveBatch(invoiceDetailEntities);
            } else {
                updateFailLogAndCollectionInfo(checkMsg, checkInvoiceDTO);
                return Response.error(checkMsg);
            }
        } else {
            updateFailLogAndCollectionInfo("发票远程查验接口调用失败", checkInvoiceDTO);
            return Response.error("PUR_ERROR_001");
        }
        return Response.success();
    }

    private void updateFailLogAndCollectionInfo(String checkMsg, CheckInvoiceDTO checkInvoiceDTO) {
        CheckLogEntity checkLogEntity = new CheckLogEntity();
        String uuid = UUIDUitl.UUID32(false);
        checkLogEntity.setUuid(uuid);
        checkLogEntity.setCheckResult(checkMsg);
        checkLogEntity.setCheckStatus(CodeConstant.CHECK_FAIL);
        checkLogEntity.setInvoiceNo(checkInvoiceDTO.getInvoiceNo());
        checkLogEntity.setInvoiceCode(checkInvoiceDTO.getInvoiceCode());
        checkLogEntity.setInvoiceType(checkInvoiceDTO.getInvoiceType());
        if (StrUtil.isNotBlank(checkInvoiceDTO.getAmountWithOutTax())) {
            checkLogEntity.setAmountWithOutTax(checkInvoiceDTO.getAmountWithOutTax());
        }
        if (StrUtil.isNotBlank(checkInvoiceDTO.getCheckCode())) {
            checkLogEntity.setCheckCode(checkInvoiceDTO.getCheckCode());
        }
        checkLogMapper.insert(checkLogEntity);
        InvoiceCollectionEntity invoiceCollectionEntity = new InvoiceCollectionEntity();
        invoiceCollectionEntity.setCheckStatus(CodeConstant.CHECK_FAIL);
        invoiceCollectionEntity.setCheckResult(checkMsg);
        invoiceCollectionEntity.setUuid(checkInvoiceDTO.getUuid());
        this.saveOrUpdate(invoiceCollectionEntity);
    }

    //处理发票查验返回的日期格式
    private String getFormatDate(String dateStr) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date date = sdf.parse(dateStr);
            return sdf2.format(date);
        } catch (ParseException e) {
            log.error("日期格式异常：{}", e);
        }
        return dateStr;
    }

    /**
     * 发票采集【上传图片识别】
     *
     * @param multipartFiles
     * @return
     */
    @Transactional
    public Response uploadInvoiceImage(List<MultipartFile> multipartFiles, String mark) throws Exception {
        if (StrUtil.isBlank(mark)) {
            mark = "0";
        }
        String buffer = "";
        for (MultipartFile multipartFile : multipartFiles) {
            InputStream inputStream = null;
            try {
                //根据图片大小压缩
//              MultipartFile multipartFile1 = ImageSizeUtil.byte2Base64StringFun(multipartFile);
                inputStream = multipartFile.getInputStream();
                ImageUploadInvoiceDTO imageUploadInvoiceDTO = new ImageUploadInvoiceDTO();
                imageUploadInvoiceDTO.setImageBase64Str(Base64Util.encode(getFileByte(inputStream)));
                Response response = apiClientService.invoiceDiscern(imageUploadInvoiceDTO);
                //T0000判断识别接口调用成功
                if (CodeConstant.T0000.equals(response.getCode())) {
                    Map imageInfo = (Map) response.getData();
                    PurchaserApiRespVO purchaserApiRespVO = BeanUtil.mapToBean(imageInfo, PurchaserApiRespVO.class, false);
                    if (CodeConstant.SUCCESS.equals(purchaserApiRespVO.getCode())) {
                        //调用上传影像接口
                        MinIOUploadResDTO dto = minIOUtils.upload(BUCKET_NAME, GROUP_INVOICE, multipartFile, true);
                        //生成影像ID
                        String imageId = dto.getMinFileName();
                        String invoiceInfo = Base64Util.decode(purchaserApiRespVO.getContent());
                        JSONArray invoiceList = JSONUtil.parseArray(invoiceInfo);
                        int invoiceNumber = invoiceList.size();
                        for (int i = 0; i < invoiceNumber; i++) {
                            JSONObject invoiceData = invoiceList.getJSONObject(i);
                            String invoiceType = invoiceData.getStr("invoice_type");
                            String invoiceNo = invoiceData.getStr("invoice_no1");
                            log.info("============="+invoiceNo);
                            Response message = new Response();
                            //mark为1，做对公ocr识别处理,只对增值税发票处理
                            if ("1".equals(mark)) {
                                if (CodeConstant.OCRINVOICE_LIST.contains(invoiceType)) {
                                    //处理增值税发票数据
                                    message = dealInvoiceData(invoiceData, imageId, mark);
                                    if ("PUR_102".equals(message.getCode())) {
                                        buffer +=multipartFile.getOriginalFilename()+":"+invoiceNo+"发票已存在！";
                                    }
                                } else {
                                    break;
                                }
                            } else {
                                if (CodeConstant.OCRINVOICE_LIST.contains(invoiceType)) {
                                    //处理增值税发票数据
                                    message = dealInvoiceData(invoiceData, imageId, mark);
                                    if ("PUR_102".equals(message.getCode())) {
                                        buffer +=multipartFile.getOriginalFilename()+":"+invoiceNo+"发票已存在！";
                                    }
                                } else {
                                    //处理非增值税发票数据
                                    message = dealOtherInvoice(invoiceData, imageId);
                                    if ("PUR_102".equals(message.getCode())) {
                                        buffer +=multipartFile.getOriginalFilename()+":"+invoiceNo+"发票已存在！";
                                    }
                                }
                            }
                        }

                    } else {
                        return Response.error(purchaserApiRespVO.getMsg());
                    }
                } else {
                    return Response.error("PUR_ERROR_003");
                }
            } catch (IOException e) {
                log.error("图片上传识别异常：{e}", e);
                return Response.error("PUR_ERROR_004");
            } finally {
                if (inputStream != null) {
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                        log.error("图片上传失败：{e}", e);
                    }
                }
            }
        }
        if (buffer!= "") {
            return Response.error("T0001",buffer);
        }
        return Response.success();
    }

    /**
     * 发票审核规则
     *
     * @param invoiceCollectionEntity
     */
    private InvoiceCollectionEntity checkInvoiceRules(InvoiceCollectionEntity invoiceCollectionEntity) {
        //校验发票规则
        InvoiceReviewRulesEntity entitySH = ReviewRulesMapper.selectOne(new QueryWrapper<InvoiceReviewRulesEntity>().eq("tax_number", invoiceCollectionEntity.getPurchaserTaxNo()));
        if (entitySH != null) {
            return reviewRulesService.rulesReview(invoiceCollectionEntity, entitySH.getUuid());
        }
        if (entitySH == null) {
            InvoiceReviewRulesEntity entityJT = ReviewRulesMapper.selectOne(new QueryWrapper<InvoiceReviewRulesEntity>().eq("scope_application", "1"));
            if (entityJT != null) {
                return reviewRulesService.rulesReview(invoiceCollectionEntity, entityJT.getUuid());
            }
        }
        return null;
    }

    //处理增值税发票数据
    private Response dealInvoiceData(JSONObject invoiceData, String imageId, String mark) {
        String uuid = UUIDUitl.UUID32(false);
        CheckInvoiceDTO checkInvoiceDTO = new CheckInvoiceDTO();
        checkInvoiceDTO.setInvoiceType(BeanSelfUtils.convertInvoiceType(invoiceData.getStr("invoice_type")));
        checkInvoiceDTO.setInvoiceCode(invoiceData.getStr("invoice_code1"));
        checkInvoiceDTO.setInvoiceNo(invoiceData.getStr("invoice_no1"));
        checkInvoiceDTO.setInvoiceDate((BeanSelfUtils.removerStr(invoiceData.getStr("create_date"))));
        checkInvoiceDTO.setAmountWithOutTax(invoiceData.getStr("total"));
        //取校验码后6位
        if (StrUtil.isNotBlank(invoiceData.getStr("check_code")) && invoiceData.getStr("check_code").length() >= 6) {
            checkInvoiceDTO.setCheckCode(invoiceData.getStr("check_code").substring(invoiceData.getStr("check_code").length() - 6));
        } else {
            checkInvoiceDTO.setCheckCode(invoiceData.getStr("check_code"));
        }
        checkInvoiceDTO.setUuid(uuid);
        //记录查验日志
        CheckLogEntity checkLogEntity = new CheckLogEntity();
        BeanUtil.copyProperties(checkInvoiceDTO, checkLogEntity);
        checkLogEntity.setUuid(UUIDUitl.UUID32(false));
        checkLogEntity.setLinkId(uuid);
        checkLogMapper.insert(checkLogEntity);
        //校验去重
        QueryWrapper<InvoiceCollectionEntity> invoiceQuery = new QueryWrapper<>();
        String invoiceCode = invoiceData.getStr("invoice_code1");
        String invoiceNo = invoiceData.getStr("invoice_no1");
        invoiceQuery.eq("invoice_code", invoiceCode);
        invoiceQuery.eq("invoice_no", invoiceNo);
        InvoiceCollectionEntity invoiceCollection = baseMapper.selectOne(invoiceQuery);
        InvoiceCollectionEntity invoiceCollectionEntity = new InvoiceCollectionEntity();
        BeanUtil.copyProperties(checkInvoiceDTO, invoiceCollectionEntity);
        if (mark != "1") {
            invoiceCollectionEntity.setReimbursementStatus(CodeConstant.REIMBURSEMENT_1);
            invoiceCollectionEntity.setPersonLiable(UserInfoUtil.getUserNickName());
            invoiceCollectionEntity.setPersonLiableId(UserInfoUtil.getUserID());
            invoiceCollectionEntity.setProcedureStatus(CodeConstant.APPROVAL_1);
        }
        invoiceCollectionEntity.setCheckStatus(CodeConstant.NOT_CHECK);
        invoiceCollectionEntity.setRulesStatus(CodeConstant.NOT_RULES);
        invoiceCollectionEntity.setCheckNumber(0);
        invoiceCollectionEntity.setUuid(uuid);
        invoiceCollectionEntity.setDataSource(CodeConstant.UPLOAD_1);
        invoiceCollectionEntity.setSubmitStatus(CodeConstant.SUBMIT_STATUS_0);
        invoiceCollectionEntity.setImageId(imageId);
        invoiceCollectionEntity.setCreateTimeStr(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        invoiceCollectionEntity.setCollector(UserInfoUtil.getUserNickName());
        invoiceCollectionEntity.setCollectorId(UserInfoUtil.getUserID());
        if ("1".equals(mark)) {
            invoiceCollectionEntity.setCollectMark(mark);
        } else {
            invoiceCollectionEntity.setCollectMark(CodeConstant.COMM_CODE_0);
        }
        if (invoiceCollection != null) {
            return Response.error("PUR_102");
            /*String reimbursementStatus = invoiceCollection.getReimbursementStatus();
            if (CodeConstant.REIMBURSEMENT_2.equals(reimbursementStatus)) {
                log.error("发票代码：{}发票号码：{}已存在且状态为已报销，请检查！", invoiceCode, invoiceNo);
                return Response.error("PUR_102");
            }else if(CodeConstant.SUBMIT_STATUS_1.equals(invoiceCollection.getSubmitStatus())){
                log.error("发票代码：{}发票号码：{}已存在且状态为已提交，请检查！", invoiceCode, invoiceNo);
                return Response.error("PUR_115");
            } else {
                String invoiceId = invoiceCollection.getUuid();
                String removeImageId = invoiceCollection.getImageId();
                //将发票影像和发票信息以及发票明细删除
                minIOUtils.removeObject(BUCKET_NAME, GROUP_INVOICE, removeImageId);
                baseMapper.deleteById(invoiceId);
                invoiceDetailService.remove(new QueryWrapper<InvoiceDetailEntity>().eq("link_id", invoiceId));
                baseMapper.insert(invoiceCollectionEntity);
                checkInvoiceSync(checkInvoiceDTO);
            }*/
        } else {
            baseMapper.insert(invoiceCollectionEntity);
            checkInvoiceSync(checkInvoiceDTO);
        }
        return Response.success();
    }

    //处理非增值税发票数据
    private Response dealOtherInvoice(JSONObject invoiceData, String imageId) {
        String invoiceType = invoiceData.getStr("invoice_type");
        Response message = new Response();
        if (CodeConstant.INVOICETYPE_HCP.equals(invoiceType)) {
            //火车票【10503】
            message = dealTrainTicket(invoiceData, imageId);
        } else if (CodeConstant.INVOICETYPE_CZP.equals(invoiceType)) {
            //出租车发票【10500】
            message = dealTaxiTicket(invoiceData, imageId);
        } else if (CodeConstant.INVOICETYPE_DEFP.equals(invoiceType)) {
            //定额发票【10200】
            message = dealQuotaTicket(invoiceData, imageId);
        } else if (CodeConstant.INVOICETYPE_FJP.equals(invoiceType)) {
            //航空运输电子客票行程单【10506】
            message = dealPlaneTicket(invoiceData, imageId);
        } else if (CodeConstant.INVOICETYPE_GLFP.equals(invoiceType)) {
            //过路费发票【10507】
            message = dealTollTicket(invoiceData, imageId);
        } else if (CodeConstant.INVOICETYPE_JDFP.equals(invoiceType)) {
            //机打发票【10400】
            message = dealMachinTicket(invoiceData, imageId);
        } else if (CodeConstant.INVOICETYPE_QCP.equals(invoiceType)) {
            //客运汽车【10505】
            message = dealBusTicket(invoiceData, imageId);
        } else {
            message.setCode("PUR_102");
        }
        return message;
    }

    //火车票解析入库【10503】
    private Response dealTrainTicket(JSONObject invoiceData, String imageId) {
        //火车票只有发票号码，没有发票代码，用乘车人姓名+发票号确定唯一
        String invoiceNo = invoiceData.getStr("invoice_no1");
        String travelName = invoiceData.getStr("name");
        QueryWrapper<TrainTicketEntity> trainQuery = new QueryWrapper<>();
        trainQuery.eq("invoice_no", invoiceNo);
        trainQuery.eq("travel_name", travelName);
        TrainTicketEntity trainTicket = trainTicketMapper.selectOne(trainQuery);
        TrainTicketEntity trainTicketEntity = new TrainTicketEntity();
        trainTicketEntity.setUuid(UUIDUitl.UUID32(false));
        trainTicketEntity.setInvoiceType(BeanSelfUtils.convertInvoiceType(invoiceData.getStr("invoice_type")));
        trainTicketEntity.setConsumeKind(invoiceData.getStr("kind"));
        trainTicketEntity.setInvoiceNo(invoiceNo);
        String travelDate = invoiceData.getStr("create_date");
        if (StrUtil.isNotBlank(travelDate)) {
            trainTicketEntity.setTravelDate(BeanSelfUtils.removerStr(travelDate));
        }
        trainTicketEntity.setTravelTime(invoiceData.getStr("time"));
        trainTicketEntity.setTravelName(travelName);
        trainTicketEntity.setFromStation(invoiceData.getStr("station_geton"));
        trainTicketEntity.setArriveStation(invoiceData.getStr("station_getoff"));
        trainTicketEntity.setTrainNumber(invoiceData.getStr("train_number"));
        trainTicketEntity.setSeatGrade(invoiceData.getStr("seat"));
        trainTicketEntity.setAmountBig(invoiceData.getStr("amount_big"));
        trainTicketEntity.setAmountSmall(invoiceData.getStr("amount_small"));
        trainTicketEntity.setSerialNumber(invoiceData.getStr("serial_number"));
        trainTicketEntity.setIdNumber(invoiceData.getStr("user_id"));
        trainTicketEntity.setImageId(imageId);
        trainTicketEntity.setCollector(UserInfoUtil.getUserNickName());
        trainTicketEntity.setCollectorId(UserInfoUtil.getUserID());
        trainTicketEntity.setPersonLiable(UserInfoUtil.getUserNickName());
        trainTicketEntity.setPersonLiableId(UserInfoUtil.getUserID());
        trainTicketEntity.setReimbursementStatus(CodeConstant.REIMBURSEMENT_1);
        trainTicketEntity.setProcedureStatus(CodeConstant.APPROVAL_1);
        trainTicketEntity.setCreateTimeStr(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        if (trainTicket != null) {
            return Response.error("PUR_102");
            /*String reimbursementStatus = trainTicket.getReimbursementStatus();
            if (CodeConstant.REIMBURSEMENT_2.equals(reimbursementStatus)) {
                return Response.error("PUR_102");
            } else {
                minIOUtils.removeObject(BUCKET_NAME, GROUP_INVOICE, trainTicket.getImageId());
                trainTicketMapper.deleteById(trainTicket.getUuid());
                trainTicketMapper.insert(trainTicketEntity);
            }*/
        } else {
            trainTicketMapper.insert(trainTicketEntity);
        }
        return Response.success();
    }

    //出租车票解析入库【10500】
    private Response dealTaxiTicket(JSONObject invoiceData, String imageId) {
        //用发票代码+发票号码确定唯一
        QueryWrapper<TaxiTicketEntity> taxiQuery = new QueryWrapper<>();
        String invoiceCode = invoiceData.getStr("invoice_code1");
        String invoiceNo = invoiceData.getStr("invoice_no1");
        taxiQuery.eq("invoice_code", invoiceCode);
        taxiQuery.eq("invoice_no", invoiceNo);
        TaxiTicketEntity taxiTicket = taxiTicketMapper.selectOne(taxiQuery);
        TaxiTicketEntity taxiTicketEntity = new TaxiTicketEntity();
        taxiTicketEntity.setUuid(UUIDUitl.UUID32(false));
        taxiTicketEntity.setInvoiceType(BeanSelfUtils.convertInvoiceType(invoiceData.getStr("invoice_type")));
        taxiTicketEntity.setConsumeKind(invoiceData.getStr("kind"));
        taxiTicketEntity.setInvoiceCode(invoiceCode);
        taxiTicketEntity.setInvoiceNo(invoiceNo);
        String createDate = invoiceData.getStr("create_date");
        if (StrUtil.isNotBlank(createDate)) {
            taxiTicketEntity.setCreateDate(BeanSelfUtils.removerStr(createDate));
        }
        taxiTicketEntity.setInvoicePlace(invoiceData.getStr("place"));
        taxiTicketEntity.setTimeGeton(invoiceData.getStr("time_geton"));
        taxiTicketEntity.setTimeGetoff(invoiceData.getStr("time_getoff"));
        taxiTicketEntity.setMileage(invoiceData.getStr("mileage"));
        taxiTicketEntity.setAmountBig(invoiceData.getStr("amount_big"));
        taxiTicketEntity.setAmountSmall(invoiceData.getStr("amount_small"));
        taxiTicketEntity.setFare(invoiceData.getStr("fare"));
        taxiTicketEntity.setSurcharge(invoiceData.getStr("surcharge"));
        taxiTicketEntity.setImageId(imageId);
        taxiTicketEntity.setCollector(UserInfoUtil.getUserNickName());
        taxiTicketEntity.setCollectorId(UserInfoUtil.getUserID());
        taxiTicketEntity.setPersonLiable(UserInfoUtil.getUserNickName());
        taxiTicketEntity.setPersonLiableId(UserInfoUtil.getUserID());
        taxiTicketEntity.setReimbursementStatus(CodeConstant.REIMBURSEMENT_1);
        taxiTicketEntity.setProcedureStatus(CodeConstant.APPROVAL_1);
        taxiTicketEntity.setCreateTimeStr(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        if (taxiTicket != null) {
            return Response.error("PUR_102");
            /*String reimbursementStatus = taxiTicket.getReimbursementStatus();
            if (CodeConstant.REIMBURSEMENT_2.equals(reimbursementStatus)) {
                return Response.error("PUR_102");
            } else {
                minIOUtils.removeObject(BUCKET_NAME, GROUP_INVOICE, taxiTicket.getImageId());
                taxiTicketMapper.deleteById(taxiTicket.getUuid());
                taxiTicketMapper.insert(taxiTicketEntity);
            }*/
        } else {
            taxiTicketMapper.insert(taxiTicketEntity);
        }
        return Response.success();
    }

    //定额票解析入库【10200】
    private Response dealQuotaTicket(JSONObject invoiceData, String imageId) {
        //用发票代码+发票号码确定唯一
        String invoiceCode = invoiceData.getStr("invoice_code1");
        String invoiceNo = invoiceData.getStr("invoice_no1");
        QueryWrapper<QuotaTicketEntity> quotaQuery = new QueryWrapper<>();
        quotaQuery.eq("invoice_code", invoiceCode);
        quotaQuery.eq("invoice_no", invoiceNo);
        QuotaTicketEntity quotaTicket = quotaTicketMapper.selectOne(quotaQuery);
        QuotaTicketEntity quotaTicketEntity = new QuotaTicketEntity();
        quotaTicketEntity.setUuid(UUIDUitl.UUID32(false));
        quotaTicketEntity.setInvoiceType(BeanSelfUtils.convertInvoiceType(invoiceData.getStr("invoice_type")));
        quotaTicketEntity.setConsumeKind(invoiceData.getStr("kind"));
        quotaTicketEntity.setInvoiceCode(invoiceCode);
        quotaTicketEntity.setInvoiceNo(invoiceNo);
        quotaTicketEntity.setAmountBig(invoiceData.getStr("amount_big"));
        quotaTicketEntity.setAmountSmall(invoiceData.getStr("amount_small"));
        quotaTicketEntity.setImageId(imageId);
        quotaTicketEntity.setCollector(UserInfoUtil.getUserNickName());
        quotaTicketEntity.setCollectorId(UserInfoUtil.getUserID());
        quotaTicketEntity.setPersonLiable(UserInfoUtil.getUserNickName());
        quotaTicketEntity.setPersonLiableId(UserInfoUtil.getUserID());
        quotaTicketEntity.setReimbursementStatus(CodeConstant.REIMBURSEMENT_1);
        quotaTicketEntity.setProcedureStatus(CodeConstant.APPROVAL_1);
        quotaTicketEntity.setCreateTimeStr(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        if (quotaTicket != null) {
            return Response.error("PUR_102");
            /*String reimbursementStatus = quotaTicket.getReimbursementStatus();
            if (CodeConstant.REIMBURSEMENT_2.equals(reimbursementStatus)) {
                return Response.error("PUR_102");
            } else {
                minIOUtils.removeObject(BUCKET_NAME, GROUP_INVOICE, quotaTicket.getImageId());
                quotaTicketMapper.deleteById(quotaTicket.getUuid());
                quotaTicketMapper.insert(quotaTicketEntity);
            }*/
        } else {
            quotaTicketMapper.insert(quotaTicketEntity);
        }
        return Response.success();
    }

    //航空运输电子客票行程单解析入库【10506】
    private Response dealPlaneTicket(JSONObject invoiceData, String imageId) {
        //机票没有发票代码，用电子客票号码+乘机人姓名确定唯一
        String invoiceNo = invoiceData.getStr("invoice_no1");
        String userName = invoiceData.getStr("user_name");
        QueryWrapper<PlaneTicketEntity> planeQuery = new QueryWrapper<>();
        planeQuery.eq("ticket_no", invoiceNo);
        planeQuery.eq("user_name", userName);
        PlaneTicketEntity planeTicket = planeTicketMapper.selectOne(planeQuery);
        PlaneTicketEntity planeTicketEntity = new PlaneTicketEntity();
        String uuid = UUIDUitl.UUID32(false);
        planeTicketEntity.setUuid(uuid);
        planeTicketEntity.setInvoiceType(BeanSelfUtils.convertInvoiceType(invoiceData.getStr("invoice_type")));
        planeTicketEntity.setConsumeKind(invoiceData.getStr("kind"));
        planeTicketEntity.setUserName(userName);
        planeTicketEntity.setIdNumber(invoiceData.getStr("user_id"));
        planeTicketEntity.setTicketNo(invoiceNo);
        planeTicketEntity.setCheckCode(invoiceData.getStr("check_code"));
        String ticketDate = invoiceData.getStr("create_date");
        if (StrUtil.isNotBlank(ticketDate)) {
            planeTicketEntity.setTicketDate(BeanSelfUtils.removerStr(ticketDate));
        }
        planeTicketEntity.setAgentCode(invoiceData.getStr("agentcode"));
        planeTicketEntity.setIssueBy(invoiceData.getStr("issue_by"));
        planeTicketEntity.setTicketPrice(invoiceData.getStr("fare"));
        planeTicketEntity.setTotalTax(invoiceData.getStr("total_tax"));
        planeTicketEntity.setFuelSurcharge(invoiceData.getStr("fuel_surcharge"));
        planeTicketEntity.setCaacDevelopmentFund(invoiceData.getStr("caac_development_fund"));
        planeTicketEntity.setInsurance(invoiceData.getStr("insurance"));
        planeTicketEntity.setInternationalFlag(invoiceData.getStr("international_flag"));
        planeTicketEntity.setPrintSerialNumber(invoiceData.getStr("print_serial_number"));
        planeTicketEntity.setAmountBig(invoiceData.getStr("amount_big"));
        planeTicketEntity.setAmountSmall(invoiceData.getStr("amount_small"));
        planeTicketEntity.setImageId(imageId);
        planeTicketEntity.setCollector(UserInfoUtil.getUserNickName());
        planeTicketEntity.setCollectorId(UserInfoUtil.getUserID());
        planeTicketEntity.setPersonLiable(UserInfoUtil.getUserNickName());
        planeTicketEntity.setPersonLiableId(UserInfoUtil.getUserID());
        planeTicketEntity.setReimbursementStatus(CodeConstant.REIMBURSEMENT_1);
        planeTicketEntity.setProcedureStatus(CodeConstant.APPROVAL_1);
        planeTicketEntity.setCreateTimeStr(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        if (planeTicket != null) {
            return Response.error("PUR_102");
            /*String reimbursementStatus = planeTicket.getReimbursementStatus();
            if (CodeConstant.REIMBURSEMENT_2.equals(reimbursementStatus)) {
                return Response.error("PUR_102");
            } else {
                minIOUtils.removeObject(BUCKET_NAME, GROUP_INVOICE, planeTicket.getImageId());
                planeTicketMapper.deleteById(planeTicket.getUuid());
                planeTicketMapper.insert(planeTicketEntity);
                dealPlaneTicketDetail(invoiceData, planeTicket.getUuid(), uuid);
            }*/
        } else {
            planeTicketMapper.insert(planeTicketEntity);
            dealPlaneTicketDetail(invoiceData, "", uuid);
        }
        return Response.success();
    }

    //处理航空运输电子客票行程单航班信息
    private void dealPlaneTicketDetail(JSONObject invoiceData, String deleteUuid, String inserUuid) {
        List<PlaneTicketDetailEntity> planeTicketDetailEntities = new ArrayList<>();
        String flights = invoiceData.getStr("flights");
        JSONArray flightsInfo = JSONUtil.parseArray(flights);
        int infoSize = flightsInfo.size();
        for (int i = 0; i < infoSize; i++) {
            JSONObject planeObject = flightsInfo.getJSONObject(i);
            PlaneTicketDetailEntity planeTicketDetailEntity = new PlaneTicketDetailEntity();
            planeTicketDetailEntity.setUuid(UUIDUitl.UUID32(false));
            planeTicketDetailEntity.setLinkId(inserUuid);
            planeTicketDetailEntity.setFromStation(planeObject.getStr("from"));
            planeTicketDetailEntity.setArriveStation(planeObject.getStr("to"));
            planeTicketDetailEntity.setFlightNumber(planeObject.getStr("flight_number"));
            String flightDate = planeObject.getStr("date");
            if (StrUtil.isNotBlank(flightDate)) {
                planeTicketDetailEntity.setFlightDate(BeanSelfUtils.removerStr(flightDate));
            }
            planeTicketDetailEntity.setFlightTime(planeObject.getStr("time"));
            planeTicketDetailEntity.setSeatGrade(planeObject.getStr("seat"));
            planeTicketDetailEntity.setCarrier(planeObject.getStr("carrier"));
            planeTicketDetailEntity.setClassName(planeObject.getStr("class_name"));
            planeTicketDetailEntity.setCreateTimeStr(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            planeTicketDetailEntities.add(planeTicketDetailEntity);
        }
        planeTicketDetailMapper.delete(new QueryWrapper<PlaneTicketDetailEntity>().eq("link_id", deleteUuid));
        planeTicketDetailService.saveBatch(planeTicketDetailEntities);
    }

    //过路费发票解析入库【10507】
    private Response dealTollTicket(JSONObject invoiceData, String imageId) {
        //用发票代码+号码确定唯一
        String invoiceCode = invoiceData.getStr("invoice_code1");
        String invoiceNo = invoiceData.getStr("invoice_no1");
        QueryWrapper<TollTicketEntity> tollQuery = new QueryWrapper<>();
        tollQuery.eq("invoice_code", invoiceCode);
        tollQuery.eq("invoice_no", invoiceNo);
        TollTicketEntity tollTicket = tollTicketMapper.selectOne(tollQuery);
        TollTicketEntity tollTicketEntity = new TollTicketEntity();
        tollTicketEntity.setUuid(UUIDUitl.UUID32(false));
        tollTicketEntity.setInvoiceType(BeanSelfUtils.convertInvoiceType(invoiceData.getStr("invoice_type")));
        tollTicketEntity.setConsumeKind(invoiceData.getStr("kind"));
        tollTicketEntity.setInvoiceCode(invoiceCode);
        tollTicketEntity.setInvoiceNo(invoiceNo);
        String travelDate = invoiceData.getStr("create_date");
        if (StrUtil.isNotBlank(travelDate)) {
            tollTicketEntity.setTravelDate(BeanSelfUtils.removerStr(travelDate));
        }
        tollTicketEntity.setTravelTime(invoiceData.getStr("time"));
        tollTicketEntity.setEntrance(invoiceData.getStr("entrance"));
        tollTicketEntity.setWayOut(invoiceData.getStr("exit"));
        tollTicketEntity.setAmountBig(invoiceData.getStr("amount_big"));
        tollTicketEntity.setAmountSmall(invoiceData.getStr("amount_small"));
        tollTicketEntity.setImageId(imageId);
        tollTicketEntity.setCollector(UserInfoUtil.getUserNickName());
        tollTicketEntity.setCollectorId(UserInfoUtil.getUserID());
        tollTicketEntity.setPersonLiable(UserInfoUtil.getUserNickName());
        tollTicketEntity.setPersonLiableId(UserInfoUtil.getUserID());
        tollTicketEntity.setReimbursementStatus(CodeConstant.REIMBURSEMENT_1);
        tollTicketEntity.setProcedureStatus(CodeConstant.APPROVAL_1);
        tollTicketEntity.setCreateTimeStr(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        if (tollTicket != null) {
            return Response.error("PUR_102");
            /*String reimbursementStatus = tollTicket.getReimbursementStatus();
            if (CodeConstant.REIMBURSEMENT_2.equals(reimbursementStatus)) {
                return Response.error("PUR_102");
            } else {
                minIOUtils.removeObject(BUCKET_NAME, GROUP_INVOICE, tollTicket.getImageId());
                tollTicketMapper.deleteById(tollTicket.getUuid());
                tollTicketMapper.insert(tollTicketEntity);
            }*/
        } else {
            tollTicketMapper.insert(tollTicketEntity);
        }
        return Response.success();
    }

    //机打发票解析入库【10400】
    private Response dealMachinTicket(JSONObject invoiceData, String imageId) {
        ////用发票代码+号码确定唯一
        String invoiceCode = invoiceData.getStr("invoice_code1");
        String invoiceNo = invoiceData.getStr("invoice_no1");
        QueryWrapper<MachinTicketEntity> machinQuery = new QueryWrapper<>();
        machinQuery.eq("invoice_code", invoiceCode);
        machinQuery.eq("invoice_no", invoiceNo);
        MachinTicketEntity machinTicket = machinTicketMapper.selectOne(machinQuery);
        MachinTicketEntity machinTicketEntity = new MachinTicketEntity();
        machinTicketEntity.setUuid(UUIDUitl.UUID32(false));
        machinTicketEntity.setInvoiceType(BeanSelfUtils.convertInvoiceType(invoiceData.getStr("invoice_type")));
        machinTicketEntity.setConsumeKind(invoiceData.getStr("kind"));
        machinTicketEntity.setInvoiceCode(invoiceCode);
        machinTicketEntity.setInvoiceNo(invoiceNo);
        machinTicketEntity.setPurchaserName(invoiceData.getStr("buyer_name"));
        machinTicketEntity.setPurchaserTaxNo(invoiceData.getStr("buyer_tax_no"));
        machinTicketEntity.setSellerName(invoiceData.getStr("seller_name"));
        machinTicketEntity.setSellerTaxNo(invoiceData.getStr("seller_tax_no"));
        machinTicketEntity.setInvoiceDate(invoiceData.getStr("create_date"));
        machinTicketEntity.setPrintedMark(invoiceData.getStr("printed_mark"));
        machinTicketEntity.setAmountBig(invoiceData.getStr("amount_big"));
        machinTicketEntity.setAmountSmall(invoiceData.getStr("amount_small"));
        machinTicketEntity.setImageId(imageId);
        machinTicketEntity.setCollector(UserInfoUtil.getUserNickName());
        machinTicketEntity.setCollectorId(UserInfoUtil.getUserID());
        machinTicketEntity.setPersonLiable(UserInfoUtil.getUserNickName());
        machinTicketEntity.setPersonLiableId(UserInfoUtil.getUserID());
        machinTicketEntity.setReimbursementStatus(CodeConstant.REIMBURSEMENT_1);
        machinTicketEntity.setProcedureStatus(CodeConstant.APPROVAL_1);
        machinTicketEntity.setCreateTimeStr(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        if (machinTicket != null) {
            return Response.error("PUR_102");
            /*String reimbursementStatus = machinTicket.getReimbursementStatus();
            if (CodeConstant.REIMBURSEMENT_2.equals(reimbursementStatus)) {
                return Response.error("PUR_102");
            } else {
                minIOUtils.removeObject(BUCKET_NAME, GROUP_INVOICE, machinTicket.getImageId());
                machinTicketMapper.deleteById(machinTicket.getUuid());
                machinTicketMapper.insert(machinTicketEntity);
            }*/
        } else {
            machinTicketMapper.insert(machinTicketEntity);
        }
        return Response.success();
    }

    //客运汽车票解析入库【10505】
    private Response dealBusTicket(JSONObject invoiceData, String imageId) {
        ////用发票代码+号码确定唯一
        String invoiceCode = invoiceData.getStr("invoice_code1");
        String invoiceNo = invoiceData.getStr("invoice_no1");
        QueryWrapper<BusTicketEntity> busQuery = new QueryWrapper<>();
        busQuery.eq("invoice_code", invoiceCode);
        busQuery.eq("invoice_no", invoiceNo);
        BusTicketEntity busTicket = busTicketMapper.selectOne(busQuery);
        BusTicketEntity busTicketEntity = new BusTicketEntity();
        busTicketEntity.setUuid(UUIDUitl.UUID32(false));
        busTicketEntity.setInvoiceType(BeanSelfUtils.convertInvoiceType(invoiceData.getStr("invoice_type")));
        busTicketEntity.setConsumeKind(invoiceData.getStr("kind"));
        busTicketEntity.setInvoiceCode(invoiceCode);
        busTicketEntity.setInvoiceNo(invoiceNo);
        String travelDate = invoiceData.getStr("create_date");
        if (StrUtil.isNotBlank(travelDate)) {
            busTicketEntity.setTravelDate(BeanSelfUtils.removerStr(travelDate));
        }
        busTicketEntity.setTravelTime(invoiceData.getStr("time"));
        busTicketEntity.setTravelName(invoiceData.getStr("name"));
        busTicketEntity.setFromStation(invoiceData.getStr("station_geton"));
        busTicketEntity.setArriveStation(invoiceData.getStr("station_getoff"));
        busTicketEntity.setAmountBig(invoiceData.getStr("amount_big"));
        busTicketEntity.setAmountSmall(invoiceData.getStr("amount_small"));
        busTicketEntity.setImageId(imageId);
        busTicketEntity.setCollector(UserInfoUtil.getUserNickName());
        busTicketEntity.setCollectorId(UserInfoUtil.getUserID());
        busTicketEntity.setPersonLiable(UserInfoUtil.getUserNickName());
        busTicketEntity.setPersonLiableId(UserInfoUtil.getUserID());
        busTicketEntity.setReimbursementStatus(CodeConstant.REIMBURSEMENT_1);
        busTicketEntity.setProcedureStatus(CodeConstant.APPROVAL_1);
        busTicketEntity.setCreateTimeStr(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        if (busTicket != null) {
            return Response.error("PUR_102");
            /*String reimbursementStatus = busTicket.getReimbursementStatus();
            if (CodeConstant.REIMBURSEMENT_2.equals(reimbursementStatus)) {
                return Response.error("PUR_102");
            } else {
                minIOUtils.removeObject(BUCKET_NAME, GROUP_INVOICE, busTicket.getImageId());
                busTicketMapper.deleteById(busTicket.getUuid());
                busTicketMapper.insert(busTicketEntity);
            }*/
        } else {
            busTicketMapper.insert(busTicketEntity);
        }
        return Response.success();
    }


    /**
     * 获取文件流
     *
     * @param in 待处理文件
     * @return
     */
    private byte[] getFileByte(InputStream in) {
        byte[] data = null;
        try {
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
        }
        return data;
    }


    /**
     * 提交报销【未报销】
     *
     * @param invoiceCollectionDTO
     * @return
     */
    public Response submitReimbursement(InvoiceCollectionDTO invoiceCollectionDTO) {
        List<String> uuidList = invoiceCollectionDTO.getUuidList();
        //获取发票走审核规则
        QueryWrapper<InvoiceCollectionEntity> query = new QueryWrapper<>();
        query.in("reimbursement_status", CodeConstant.NOT_REIMBURSEMENT);
        query.eq("check_status", CodeConstant.CHECK_SUCCESS);
        query.in("uuid", uuidList);
        List<InvoiceCollectionEntity> invoices = baseMapper.selectList(query);
        if (invoices.size() == 0) {
            return Response.error(CodeConstant.T0001,"此发票查验未通过,无法提交！");
        }
        //审核强制条件通过的发票可以提交至发票池
        List<InvoiceCollectionEntity> poolList = new ArrayList<>();
        for (InvoiceCollectionEntity invoice : invoices) {
            if(!CodeConstant.RULES_SUCCESS.equals(invoice.getRulesStatus())){
                //校验发票规则
                CheckInfoRespVO vo = new CheckInfoRespVO();
                InvoiceReviewRulesEntity entitySH = reviewRulesMapper.selectOne(new QueryWrapper<InvoiceReviewRulesEntity>().eq("tax_number", invoice.getPurchaserTaxNo()));
                if (entitySH != null) {
                    vo = rulesReview.checkSubmit(invoice, entitySH.getUuid());
                }
                if (entitySH == null) {
                    InvoiceReviewRulesEntity entityJT = reviewRulesMapper.selectOne(new QueryWrapper<InvoiceReviewRulesEntity>().eq("scope_application", "1"));
                    vo = rulesReview.checkSubmit(invoice, entityJT.getUuid());
                }
                if(!vo.isGoing()){
                    return Response.error(CodeConstant.T0001,vo.getMsg());
                }
            }
            poolList.add(invoice);
        }
        //校验发票是否已经存在发票池
        StringBuilder stringBuilder = new StringBuilder();
        String msg = "以下发票已存在发票池:";
        for(InvoiceCollectionEntity entity : poolList){
            QueryWrapper<InvoicePoolEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("invoice_no",entity.getInvoiceNo())
                    .eq("invoice_code",entity.getInvoiceCode());
            //提示已存在发票池的发票号码和发票代码
            if(invoicePoolService.count(queryWrapper)>0){
                stringBuilder.append("("+entity.getInvoiceCode()+","+entity.getInvoiceNo()+")");
            }
        }
        if(!StrUtil.hasBlank(stringBuilder.toString())){
            return Response.error(CodeConstant.T0001,msg+stringBuilder.toString());
        }
        //提交报销，更新采集表报销状态为已报销，并且数据入池
        List<InvoicePoolEntity> invoicePoolEntities = new ArrayList<>();
        for (InvoiceCollectionEntity invoiceCollectionEntity : poolList) {
            InvoicePoolEntity invoicePoolEntity = new InvoicePoolEntity();
            BeanUtil.copyProperties(invoiceCollectionEntity, invoicePoolEntity);
            invoicePoolEntity.setUuid(UUIDUitl.UUID32(false));
            invoicePoolEntity.setReimbursementStatus(CodeConstant.REIMBURSEMENT_2);
            invoicePoolEntity.setSubmitStatus(CodeConstant.SUBMIT_STATUS_1);
            invoicePoolEntities.add(invoicePoolEntity);
        }
        poolList.forEach(invoice -> {
            invoice.setReimbursementStatus(CodeConstant.REIMBURSEMENT_2);
            invoice.setSubmitUserId(UserInfoUtil.getUserID());
            invoice.setSubmitStatus(CodeConstant.SUBMIT_STATUS_1);
            invoice.setSubmitDate(DateTimeUtil.getCurrent());
        });
        invoicePoolService.saveBatch(invoicePoolEntities);
        this.updateBatchById(poolList);
        return Response.success();
    }

    /**
     * 责任人、记账科目、授权报销设置【未报销】
     *
     * @param invoiceCollectionDTO
     * @return
     */
    public Response personLiable(InvoiceCollectionDTO invoiceCollectionDTO) {
        String updateFlag = invoiceCollectionDTO.getUpdateFlag();
        if (StrUtil.isNotBlank(updateFlag)) {
            InvoiceCollectionEntity invoiceCollectionEntity = new InvoiceCollectionEntity();
            if (CodeConstant.FLAG_ZRR.equals(updateFlag)) {
                //责任人设置
                invoiceCollectionEntity.setPersonLiable(invoiceCollectionDTO.getPersonLiable());
                invoiceCollectionEntity.setPersonLiableId(invoiceCollectionDTO.getPersonLiableId());
            } else if (CodeConstant.FLAG_JZKM.equals(updateFlag)) {
                //记账科目设置
                invoiceCollectionEntity.setBookingAccount(invoiceCollectionDTO.getBookingAccount());
            } else if (CodeConstant.FLAG_SQR.equals(updateFlag)) {
                //被授权人设置
                List<String> licenseeList = invoiceCollectionDTO.getLicenseeList();
                List<String> licenseeIdList = invoiceCollectionDTO.getLicenseeIdList();
                if (CollUtil.isNotEmpty(licenseeList) && CollUtil.isNotEmpty(licenseeIdList)) {
                    String licensee = licenseeList.stream().map(String::valueOf).collect(Collectors.joining(","));
                    String licenseeId = licenseeIdList.stream().map(String::valueOf).collect(Collectors.joining(","));
                    invoiceCollectionEntity.setLicensee(licensee);
                    invoiceCollectionEntity.setLicenseeId(licenseeId);
                } else {
                    return Response.error("PUR_112");
                }
            }
            UpdateWrapper<InvoiceCollectionEntity> invoiceUpdate = new UpdateWrapper<>();
            invoiceUpdate.in("uuid", invoiceCollectionDTO.getUuidList());
            this.update(invoiceCollectionEntity, invoiceUpdate);
        } else {
            return Response.error("PUR_107");
        }
        return Response.success();
    }


    /**
     * 申请驳回【已报销】
     *
     * @param invoiceCollectionDTO
     * @return
     */
    public Response applicationRejected(InvoiceCollectionDTO invoiceCollectionDTO) {
        List<String> uuidList = invoiceCollectionDTO.getUuidList();
        List<InvoiceCollectionEntity> invoiceCollectionEntities = baseMapper.selectList(new QueryWrapper<InvoiceCollectionEntity>().in("uuid", uuidList).notIn("procedure_status", CodeConstant.APPROVAL_5));
        if (invoiceCollectionEntities == null || invoiceCollectionEntities.isEmpty() || uuidList.size() != invoiceCollectionEntities.size()) {
            return Response.error("PUR_110");
        }
        //生成申请单号
        String recordNo = UUIDUitl.UUID16(false);
        for (InvoiceCollectionEntity invoiceCollectionEntity : invoiceCollectionEntities) {
            ApplicationRecordDetailEntity applicationRecordDetailEntity = new ApplicationRecordDetailEntity();
            applicationRecordDetailEntity.setUuid(UUIDUitl.UUID32(false));
            applicationRecordDetailEntity.setRecordNo(recordNo);
            applicationRecordDetailEntity.setInvoiceType(invoiceCollectionEntity.getInvoiceType());
            applicationRecordDetailEntity.setInvoiceCode(invoiceCollectionEntity.getInvoiceCode());
            applicationRecordDetailEntity.setInvoiceNo(invoiceCollectionEntity.getInvoiceNo());
            applicationRecordDetailMapper.insert(applicationRecordDetailEntity);
        }
        ApplicationRecordEntity applicationRecordEntity = new ApplicationRecordEntity();
        applicationRecordEntity.setUuid(UUIDUitl.UUID32(false));
        applicationRecordEntity.setRecordNo(recordNo);
        applicationRecordEntity.setApplicationDate(invoiceCollectionDTO.getApplicationDate());
        applicationRecordEntity.setApplicationReasons(invoiceCollectionDTO.getApplicationReasons());
        applicationRecordEntity.setApplicationPerson(UserInfoUtil.getUserNickName());
        applicationRecordEntity.setApprovalStatus(CodeConstant.APPROVAL_1);
        applicationRecordEntity.setTicketTypes(CodeConstant.TICKET_TYPES);
        applicationRecordEntity.setCreateTimeStr(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        applicationRecordMapper.insert(applicationRecordEntity);
        invoiceCollectionEntities.forEach(invoiceCollectionEntity -> {
            invoiceCollectionEntity.setProcedureStatus(CodeConstant.APPROVAL_5);
        });
        this.updateBatchById(invoiceCollectionEntities);
        return Response.success();
    }

    /**
     * 发票影像查询
     *
     * @param invoiceImageDTO
     * @return
     */
    public Response getInvoiceImage(InvoiceImageDTO invoiceImageDTO) throws Exception {
        String dataSource = invoiceImageDTO.getDataSource();
        String imageId = invoiceImageDTO.getImageId();
        String uuid = invoiceImageDTO.getUuid();
        PurchaserInvoiceInfoRespVO purchaserInvoiceInfoRespVO = new PurchaserInvoiceInfoRespVO();
        if (CodeConstant.UPLOAD_1.equals(dataSource)) {
            InputStream fileInputStream = instance.getObject(BUCKET_NAME, GROUP_INVOICE + "/" + imageId);
            //InputStream fileInputStream = instance.getObject(GetObjectArgs.builder().bucket(BUCKET_NAME).object(GROUP_INVOICE + "/" + imageId).build());
            if (StrUtil.isBlank(imageId)) {
                return Response.error("PUR_107");
            }
            String contentType = imageId.substring(imageId.lastIndexOf(".") + 1).toLowerCase();
            String imageStr = null;
            if ("pdf".equals(contentType)) {
                imageStr = PdfchangeOneImg.useStream(fileInputStream);
                contentType = "jpg";
            } else {
                imageStr = "data:image/" + contentType + ";base64," + FileToBase64.getBase64FromInputStream(fileInputStream);
            }
            List<InvoiceDetailEntity> invoiceDetailEntities = invoiceDetailService.list(new QueryWrapper<InvoiceDetailEntity>().eq("link_id", uuid));
            purchaserInvoiceInfoRespVO.setImageStr(imageStr);
            purchaserInvoiceInfoRespVO.setInvoiceDetailEntities(invoiceDetailEntities);
            purchaserInvoiceInfoRespVO.setImageType(contentType);
            return Response.success(purchaserInvoiceInfoRespVO);
        } else {
            InvoiceCollectionEntity invoiceCollectionEntity = this.getById(uuid);
            if (invoiceCollectionEntity == null) {
                return Response.error("PUR_107");
            }
            if (!CodeConstant.CHECK_SUCCESS.equals(invoiceCollectionEntity.getCheckStatus())) {
                Response.warn(ResultConstant.RET_P0012_CODE, ResultConstant.RET_P0012_MSG);
            }
            List<InvoiceDetailEntity> invoiceDetailEntities = invoiceDetailService.list(new QueryWrapper<InvoiceDetailEntity>().eq("link_id", uuid));
            BufferedImage bufferedImage;
            if (CodeConstant.INVOICE_JSFP.equals(invoiceCollectionEntity.getInvoiceType())) {
                //卷票
                URL imgUrl = this.getClass().getResource("/image/jp.jpg");
                bufferedImage = GraphicsInvoiceUtil.graphicsForVolumeInvoiceImage(invoiceCollectionEntity, invoiceDetailEntities, imgUrl);
            } else {
                URL imgUrl = this.getClass().getResource("/image/common.jpg");
                bufferedImage = GraphicsInvoiceUtil.graphicsGenerationForInvoiceImage(invoiceCollectionEntity, invoiceDetailEntities, imgUrl);
            }
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            ImageIO.write(bufferedImage, "jpg", os);
            InputStream in = new ByteArrayInputStream(os.toByteArray());
            String imageStr = "data:image/jpg;base64," + FileToBase64.getBase64FromInputStream(in);
            purchaserInvoiceInfoRespVO.setImageStr(imageStr);
            purchaserInvoiceInfoRespVO.setInvoiceDetailEntities(invoiceDetailEntities);
            return Response.success(purchaserInvoiceInfoRespVO);
        }
    }

    /**
     * 查询所有发票信息
     *
     * @param
     * @return
     */
    public Response invoiceCollectionQueryAll(PageRequest<InvoiceCollectionQueryAllDTO> query) {
        //权限处理
//        if(StrUtil.isNotBlank(UserInfoUtil.getUserID())){
//             if(CodeConstant.GENERAL_TYPE.equals(UserInfoUtil.getUserType())){
//                invoiceQuery.and((invoice ->
//                        invoice.eq("person_liable_id", UserInfoUtil.getUserID())//责任人
//                                .or().eq("collector_id", UserInfoUtil.getUserID())//采集人
//                                .or().like("licensee_id", UserInfoUtil.getUserID())));//被授权人
//            }
//        }
        //时间处理
        if (StrUtil.isNotBlank(query.getInfo().getCreateTime())) {
            query.getInfo().setCreateTimeStartStr(query.getInfo().getCreateTime() + " 00:00:00");
            query.getInfo().setCreateTimeEndStr(query.getInfo().getCreateTime() + " 23:59:59");
        }
        List<InvoiceCollectionQueryAllVO> list = baseMapper.invoiceCollectionQueryAll(query);
        return Response.success(list);
    }

    /**
     * 发票提交至发票池
     *
     * @param invoiceCollectionDTO
     * @return
     */
    public Response submitToPool(InvoiceCollectionDTO invoiceCollectionDTO) {
        QueryWrapper<InvoiceCollectionEntity> query = new QueryWrapper<>();
        List<String> uuidList = invoiceCollectionDTO.getUuidList();
        query.eq("check_status", CodeConstant.CHECK_SUCCESS)
                .eq("rules_status", CodeConstant.RULES_SUCCESS)
                .in("uuid", uuidList);
        List<InvoiceCollectionEntity> invoiceCollectionEntities = this.list(query);
        //校验提交数据
        if (invoiceCollectionEntities == null
                || invoiceCollectionEntities.isEmpty()
                || invoiceCollectionEntities.size() != uuidList.size()) {
            return Response.error("PUR_116");
        }
        ArrayList<HashMap<String, String>> list = new ArrayList<>();
        HashMap<String, String> map = new HashMap<>();
        invoiceCollectionEntities.stream().forEach(item -> {
            map.put("code", item.getInvoiceCode());
            map.put("no", item.getInvoiceNo());
            list.add(map);
        });
        //检查发票池是否已存在该发票
        for (HashMap item : list) {
            QueryWrapper<InvoicePoolEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("invoice_code", item.get("code"))
                    .eq("invoice_no", item.get("no"));
            if (invoicePoolService.count(queryWrapper) > 0) {
                return Response.error("PUR_114");
            }
        }
        //提交数据入池
        List<InvoicePoolEntity> invoicePoolEntities = new ArrayList<>();
        for (InvoiceCollectionEntity invoiceCollectionEntity : invoiceCollectionEntities) {
            InvoicePoolEntity invoicePoolEntity = new InvoicePoolEntity();
            BeanUtil.copyProperties(invoiceCollectionEntity, invoicePoolEntity);
            invoicePoolEntity.setUuid(UUIDUitl.UUID32(false));
            invoicePoolEntity.setReimbursementStatus(CodeConstant.REIMBURSEMENT_2);
            invoicePoolEntity.setSubmitStatus(CodeConstant.SUBMIT_STATUS_1);
            invoicePoolEntities.add(invoicePoolEntity);
        }
        invoiceCollectionEntities.forEach(invoice -> {
            invoice.setReimbursementStatus(CodeConstant.REIMBURSEMENT_2);
            invoice.setSubmitUserId(UserInfoUtil.getUserID());
            invoice.setSubmitStatus(CodeConstant.SUBMIT_STATUS_1);
        });
        invoicePoolService.saveBatch(invoicePoolEntities);
        this.updateBatchById(invoiceCollectionEntities);
        return Response.success();
    }

    /**
     * 发票采集查询（对公）
     *
     * @param query
     * @return
     */
    public Response queryByMark(PageRequest<InvoiceCollectionDTO> query) {
        QueryWrapper<InvoiceCollectionEntity> invoiceQuery = new QueryWrapper<>();
        InvoiceCollectionDTO invoiceCollectionDTO = query.getInfo();
        if (StrUtil.isNotBlank(invoiceCollectionDTO.getInvoiceNo())) {
            invoiceQuery.eq("invoice_no", invoiceCollectionDTO.getInvoiceNo());
        }
        if (StrUtil.isNotBlank(invoiceCollectionDTO.getCheckStatus())) {
            invoiceQuery.eq("check_status", invoiceCollectionDTO.getCheckStatus());
        }
        String createTimeStrStart = invoiceCollectionDTO.getCreateTimeStartStr();
        String createTimeStrEnd = invoiceCollectionDTO.getCreateTimeEndStr();
        if (StrUtil.isNotBlank(createTimeStrStart) && StrUtil.isNotBlank(createTimeStrEnd)) {
            invoiceQuery.between("create_time_str", createTimeStrStart + timeStart, createTimeStrEnd + timeEnd);
        }
        List<String> taxNos = commService.getTaxNumbers();
        invoiceQuery.in("purchaser_tax_no", taxNos).or().eq("collector_id",UserInfoUtil.getUserID());
        /*invoiceQuery.eq("collect_mark", invoiceCollectionDTO.getMark())
                    .eq("submit_status","0")
                    .eq("collector_id",UserInfoUtil.getUserID());*/
        IPage<InvoiceCollectionEntity> invoiceCollectionEntities = PageHelp.siamplePage(this, invoiceQuery, query.getPage(), InvoiceCollectionEntity.class);
        return Response.success(invoiceCollectionEntities);
    }
}
